import { defineStore } from 'pinia'
import { deviceInfo } from '@/api/index'
// 变浅颜色值
function getLightColor(color, level) {
  let rgb = hexToRgb(color)
  for (let i = 0; i < 3; i++) {
    rgb[i] = Math.floor((255 - rgb[i]) * level + rgb[i])
  }
  return rgbToHex(rgb[0], rgb[1], rgb[2])
}
function hexToRgb(str) {
  str = str.replace('#', '')
  let hexs = str.match(/../g)
  for (let i = 0; i < 3; i++) {
    hexs[i] = parseInt(hexs[i], 16)
  }
  return hexs
}

function rgbToHex(r, g, b) {
  return (
    '#' +
    [r, g, b]
      .map((x) => x.toString(16).padStart(2, '0'))
      .join('')
      .toUpperCase()
  )
}
export const useConfigStore = defineStore('config', {
  state: () => ({
    config: null, // 存储配置文件内容
    autoReback: false, // 是否自动返回
    topics: {
      title: '',
      subjectId: '', // 主题ID
      logId: '', // 日志ID, 打印时需要
      mainColor: '#F1746B',
      bgColor: '#EE5247',
      homeBg: '',
      waitUrl: ''
    },
    deviceInfo: {
      site: '',
      deviceName: ''
    }
  }),
  actions: {
    setConfig(data) {
      this.config = data
    },
    setReback(data) {
      this.autoReback = data
    },
    setLogId(data) {
      this.topics.logId = data
    },
    setDeviceInfo(data) {
      this.deviceInfo = data
    },
    setTopic(data) {
      this.topics = data
      this.setDeviceInfo({
        site: data.site || '',
        deviceName: data.deviceName || ''
      })
    },
    async init() {
      try {
        const res = await deviceInfo()
        console.log('获取设备信息:', res)
        if (res && res.data) {
          const info = {
            title: res.data.subjectName,
            subjectId: res.data.subjectId,
            logId: '',
            mainColor: getLightColor(res.data.mainColor, 0.2),
            bgColor: res.data.mainColor,
            homeBg: res.data.homeBackUrl,
            waitUrl: res.data.waitUrl || '',
            site: res.data?.site || '',
            deviceName: res.data?.deviceName || ''
          }
          this.setTopic(info)
          // localStorage.setItem('deviceInfo', JSON.stringify(info))
        }
      } catch (error) {
        console.error('获取设备信息失败:', error)
      }
    }
  }
})
